﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.IO;
using System.Configuration;
using WcfContrib.Extensions.OutputControllers;
using WcfContrib.Extensions.Context;
using WcfContrib.Configuration;

namespace WcfContrib.Extensions.Inspectors
{
    abstract class OutputInspectorBase : IOutputInspector
    {
        const string LogFolderPathConfigKey = "WcfContrib.Extensions.OutputLogFolder";
        const string DefaultLogFilename = "MessageTracingLog-{0}.{1:dd-MM-yyyy}.log";

        bool loadedPath;
        string finalPath;

        public IEnumerable<IOutputController> Controllers { get; set; }

        public OutputInspectorBase()
        {
            Controllers = new IOutputController[0];
        }

        public abstract string BuildRequestMessageOutput(Message request, out object correlationState, out bool processMessage, out Dictionary<OutputArgument, object> outputState);
        
        public abstract string BuildReplyMessageOutput(Message reply, object correlationState, out bool processMessage, out Dictionary<OutputArgument, object> outputState);

        string GetDefaultLogFilePath()
        {
            ActivationContextExtension context = ActivationContextExtension.Current;

            string fileName = string.Format(DefaultLogFilename, context.ServiceName, DateTime.Now);
            finalPath = Path.Combine(GetDefaultLogFolderPath(), fileName);

            return finalPath;
        }

        string GetDefaultLogFolderPath()
        {
            if (loadedPath)
            {
                return finalPath;
            }

            string currentPath = WcfContribConfigurationSection.GetSection().Extensions.LogTrace.LogFolderPath;

            if (string.IsNullOrEmpty(currentPath))
            {
                currentPath = ConfigurationManager.AppSettings[LogFolderPathConfigKey];

                if (string.IsNullOrEmpty(currentPath))
                {
                    currentPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    currentPath = Path.GetDirectoryName(currentPath);
                }
            }

            finalPath = currentPath;
            loadedPath = true;

            return currentPath;
        }

        protected void SetBasicSettings(out Dictionary<OutputArgument, object> outputState)
        {
            outputState = new Dictionary<OutputArgument, object>();

            outputState.Add(OutputArgument.TextLogFile, GetDefaultLogFilePath());
        }
    }
}
